<template>
  <div>
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="24" :md="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon class="title-icon">
                  <User />
                </el-icon>
                <span>个人信息</span>
              </div>
              <div class="header-actions">
                <el-button v-if="!isEditing" type="primary" @click="enterEditMode" :icon="Edit">编辑</el-button>
                <el-button v-else type="success" @click="saveProfile" :icon="Check">保存</el-button>
                <el-button v-if="isEditing" @click="cancelEdit" :icon="Close">取消</el-button>
              </div>
            </div>
          </template>

          <!-- 查看模式 -->
          <div v-if="!isEditing" class="profile-view">
            <div class="avatar-section">
              <div class="avatar-wrapper">
                <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar-display" />
                <div v-else class="avatar-placeholder">
                  <el-icon class="avatar-placeholder-icon">
                    <User />
                  </el-icon>
                </div>
              </div>
            </div>

            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">用户名</span>
                <span class="info-value">{{ profileForm.username }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">真实姓名</span>
                <span class="info-value">{{ profileForm.realName || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">邮箱</span>
                <span class="info-value">{{ profileForm.email || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">手机号</span>
                <span class="info-value">{{ profileForm.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">所属部门</span>
                <span class="info-value">{{ formatArrayData(profileForm.department) || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">所属角色</span>
                <span class="info-value">{{ formatArrayData(profileForm.roles) || '未设置' }}</span>
              </div>
            </div>
          </div>

          <!-- 编辑模式 -->
          <el-form
            v-else
            ref="formRef"
            :model="profileForm"
            :rules="rules"
            label-width="100px"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="24" class="avatar-section">
                <div class="avatar-wrapper">
                  <el-upload
                    class="avatar-uploader"
                    action="/api/upload/image"
                    :show-file-list="false"
                    :headers="uploadHeaders"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                  <div class="avatar-text">点击上传头像</div>
                </div>
              </el-col>

              <el-col :span="24" :md="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="profileForm.username" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="24" :md="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="profileForm.realName" />
                </el-form-item>
              </el-col>

              <el-col :span="24" :md="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" />
                </el-form-item>
              </el-col>

              <el-col :span="24" :md="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="profileForm.phone" />
                </el-form-item>
              </el-col>

              <el-col :span="24" class="form-actions">
                <el-button type="primary" @click="handleSubmit">保存</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>

      <!-- 修改密码卡片 -->
      <el-col :span="24" :md="8">
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <div class="header-title">
                <el-icon class="title-icon">
                  <Lock />
                </el-icon>
                <span>修改密码</span>
              </div>
            </div>
          </template>

          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="80px"
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入原密码"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请确认新密码"
              />
            </el-form-item>

            <el-form-item class="password-actions">
              <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
              <el-button @click="handleResetPassword">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Plus, User, Lock, Edit, Check, Close } from "@element-plus/icons-vue";
import { useAuthStore } from "@/stores/auth";
import { updateUser, getUserInfo } from "@/api/user";
import { changePassword } from "@/api/auth";

const authStore = useAuthStore();
const formRef = ref();
const passwordFormRef = ref();

// 编辑模式状态
const isEditing = ref(false);

// 保存原始数据用于取消编辑
const originalProfileData = reactive({
  username: "",
  realName: "",
  email: "",
  phone: "",
  avatar: "",
  department: "",
  roles: [],
});

const profileForm = reactive({
  username: "",
  realName: "",
  email: "",
  phone: "",
  avatar: "",
  department: "",
  roles: [],
});

const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const rules = {
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

const passwordRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 上传请求头
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${authStore.token}`,
}));

// 初始化表单数据
const initFormData = async () => {
  try {
    // 调用getUserInfo接口获取完整用户信息
    const response = await getUserInfo(authStore.userInfo.id);
    const user = response;
    profileForm.username = user.username;
    profileForm.realName = user.realName || "";
    profileForm.email = user.email || "";
    profileForm.phone = user.phone || "";
    profileForm.avatar = user.avatar || "";
    profileForm.department = user.department || "";
    profileForm.roles = user.roles || [];

    // 更新store中的用户信息
    authStore.updateUserInfo(user);

    // 保存原始数据
    Object.assign(originalProfileData, profileForm);
  } catch (error) {
    ElMessage.error("获取用户信息失败");
    // 如果API调用失败，使用store中的数据作为后备
    const user = authStore.userInfo;
    if (user) {
      profileForm.username = user.username;
      profileForm.realName = user.realName || "";
      profileForm.email = user.email || "";
      profileForm.phone = user.phone || "";
      profileForm.avatar = user.avatar || "";
      profileForm.department = user.department || "";
      profileForm.roles = user.roles || [];
      Object.assign(originalProfileData, profileForm);
    }
  }
};

// 重置表单数据
const resetFormData = () => {
  profileForm.username = "";
  profileForm.realName = "";
  profileForm.email = "";
  profileForm.phone = "";
  profileForm.avatar = "";
};

// 进入编辑模式
const enterEditMode = () => {
  // 保存当前数据为原始数据
  Object.assign(originalProfileData, profileForm);
  isEditing.value = true;
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  // 恢复原始数据
  Object.assign(profileForm, originalProfileData);
  formRef.value?.clearValidate();
};

// 头像上传成功处理
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    profileForm.avatar = response.data[0].url;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(response.message || "头像上传失败");
  }
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 保存个人信息
const saveProfile = async () => {
  try {
    await formRef.value.validate();

    // 调用API更新用户信息
    await updateUser(authStore.userInfo.id, {
      realName: profileForm.realName,
      email: profileForm.email,
      phone: profileForm.phone,
      avatar: profileForm.avatar,
    });

    // 更新store中的用户信息
    authStore.userInfo.realName = profileForm.realName;
    authStore.userInfo.email = profileForm.email;
    authStore.userInfo.phone = profileForm.phone;
    authStore.userInfo.avatar = profileForm.avatar;

    // 保存当前数据为原始数据
    Object.assign(originalProfileData, profileForm);

    // 退出编辑模式
    isEditing.value = false;

    ElMessage.success("个人信息更新成功");
  } catch (error) {
    ElMessage.error(error.message || "更新失败");
  }
};

// 原来的handleSubmit方法保持不变，但实际使用saveProfile
const handleSubmit = async () => {
  saveProfile();
};

const handleReset = () => {
  initFormData();
};

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate();

    // 调用API修改密码
    await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    ElMessage.success("密码修改成功");
    handleResetPassword();
  } catch (error) {
    ElMessage.error(error.message || "修改失败");
  }
};

const handleResetPassword = () => {
  passwordForm.oldPassword = "";
  passwordForm.newPassword = "";
  passwordForm.confirmPassword = "";
};

// 格式化数组数据显示
const formatArrayData = (data) => {
  if (!data || data.length === 0) return "";
  if (Array.isArray(data)) {
    return data.map((item) => item.name || item).join(", ");
  }
  return data.name || data;
};

onMounted(() => {
  initFormData();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 120px);
}

.profile-card,
.password-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  background: #fff;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 20px;
  color: var(--el-color-primary);
}

.header-title span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.avatar-uploader .avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.avatar-uploader .el-upload {
  border: 2px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  background: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
  background: #f0f7ff;
}

.avatar-uploader .el-upload:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: var(--el-color-primary);
  width: 120px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f2ff 100%);
}

.avatar-text {
  font-size: 14px;
  color: var(--el-color-primary);
  font-weight: 500;
}

.profile-view {
  padding: 40px 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  margin-top: 32px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.avatar-display {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-placeholder {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f2ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-placeholder-icon {
  font-size: 48px;
  color: var(--el-color-primary);
}

.profile-form,
.password-form {
  padding: 20px 0;
}

.form-actions,
.password-actions {
  text-align: center;
  margin-top: 30px;
}

.form-actions .el-button,
.password-actions .el-button {
  margin: 0 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 动画效果 */
.profile-card,
.password-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.profile-card:hover,
.password-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

/* 表单元素美化 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
}
</style>